package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 实现认证授权类
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username)  {
        //查询用户信息：通过用户名
        User user = userService.findUserByName(username);
        if (user == null) {
            return null;
        }
        //获取角色信息
        Set<Role> roles = user.getRoles();
        List<GrantedAuthority> list = new ArrayList<>();
        if (roles != null) {
            for (Role role : roles) {
                //获取权限信息
                if (role != null) {
                    Set<Permission> permissionSet = role.getPermissions();
                    //封装权限信息
                    if (permissionSet != null) {
                        for (Permission permission : permissionSet) {
                            list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                        }
                    }
                }
            }
        }
        //返回UserDetails
        org.springframework.security.core.userdetails.User userDetail = new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);
        return userDetail;
    }
}
